﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Common.Json
{
    /// <summary>
    /// Newtonsoft.Json.JObject
    /// </summary>
    public static class JObjectExtensionFunctions
    {
        /// <summary>
        /// 获取字符串值
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetString(this JObject jo, string propertyName)
        {
            var jt = jo[propertyName];
            if (jt == null)
            {
                return null;
            }
            if (jt.Type == JTokenType.Object || jt.Type == JTokenType.Array || jt.Type == JTokenType.Property)
            {
                return jt.ToString(Formatting.None);
            }
            return jt.ToString();
        }
        /// <summary>
        /// 获取整数
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static int? GetInt(this JObject jo, string propertyName)
        {
            string str = jo.GetString(propertyName);
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            int val;
            if (!int.TryParse(str, out val))
            {
                return null;
            }
            return val;
        }
        /// <summary>
        /// 获取整数
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="propertyName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int GetInt(this JObject jo, string propertyName, int defaultValue)
        {
            return GetInt(jo, propertyName) ?? defaultValue;
        }
        /// <summary>
        /// 获取高精度十进制
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static decimal? GetDecimal(this JObject jo, string propertyName)
        {
            string str = jo.GetString(propertyName);
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            decimal val;
            if (!decimal.TryParse(str, out val))
            {
                return null;
            }
            return val;
        }
        /// <summary>
        /// 获取高精度十进制
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="propertyName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static decimal GetDecimal(this JObject jo, string propertyName, decimal defaultValue)
        {
            return GetDecimal(jo, propertyName) ?? defaultValue;
        }
    }
}
